package com.defysoft.waukids.intro;

import java.io.IOException;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.BasicInfo;
import com.defysoft.waukids.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class Intro_Intro_A extends BaseActivity {

	private GoogleCloudMessaging gcm; // gcm uuid 얻기 위해 선언한 메소드들에 사용.
	String regId = null; // uuid담을 변수.
	String email = "";// SharedPreferences 에저장된 아이디 받음.
	String pass = "";// SharedPreferences 에저장된 비번 받음.
	boolean autologin = false; // 자동로그인여부.
	private SharedPreferences member; // 맴버내용 담을곳.
	private SharedPreferences school; // 유치원내용 담을곳.

	private final int UPDATE_VERSION = 7;
	private final int FAIR_VERSION = 6;
	private final int SELECT_STARTACTIVITY = 8; // 저장된 정보 확인완료 되어 원생 선택 페이지로 이동
	private final int LOGIN_CHECK = 9; // 저장된 정보있는지 검사흐름 (boolean autologin
										// 으로구분)
	private final int LOGIN_STARTACTIVITY = 10; // 저장된 정보 없거나 잘못되서 로그인페이지로 이동

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro__intro_);

		setStartData();
	}

	@Override
	public void setStartData() {
		super.setStartData();

		member = getSharedPreferences("member", MODE_PRIVATE); // 선언.
		school = getSharedPreferences("school", MODE_PRIVATE); // 선언.
		((TextView) findViewById(R.id.WAUKIDS_VERSION)).setText("appversion : "
				+ getVersion());
		checkPreferences(); // member 으로 자동로그인 여부 검사. autologin true,false
		if (checkPlayServices()) {
			registerInBackground(); // uuid생성. 후 LOGIN_CHECK
		} else {
			regId = ""; // uuid 없이.
			Toast.makeText(this, "구글 푸시서비스 사용불가능", Toast.LENGTH_LONG).show();
			sendMessage(LOGIN_CHECK);
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		if (firstThread != null) {
			firstThread.interrupt();
		}
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {

				if (checkVersion()) {
					switch (cho) {
					case 1: // 쉐어프리퍼런스 내용있음. 비교스레드.
						mainThread();
						break;
					case 2:

						onNetworkCallback(LOGIN_STARTACTIVITY, "");
						break;
					}
				}
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
					.show();
			break;

		case SELECT_STARTACTIVITY: // 저장된 정보 확인완료 되어 원생 선택 페이지로 이동
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			if (!member.getString("Mem_Confirm", "0").equals("1")) {

			} else if (member.getString("Mem_Rank", "0").equals("3")) { // 부모이면
				startActivity(new Intent(this, Intro_SelectStudent_A.class)); // 다음액티비티로가면현재액티비티끝.
				finish();
			} else if (!member.getString("Mem_Rank", "0").equals("0")) { // 원장,선생은
																			// 메인으로.
				startActivity(new Intent(this, Intro_Main_A.class));
				finish();
			} else if (member.getString("Mem_Rank", "0").equals("0")) { // 원장인증대기.
				Toast.makeText(this, "아직 유치원에 연결되지 않은 원장님정보입니다. 관리자에 문의해주세요",
						Toast.LENGTH_LONG).show();
				sendMessage(LOGIN_STARTACTIVITY); // 로그인창.
			} else if (member.getString("Mem_Rank", "0").equals("2")
					&& member.getString("FK_Cla_Mem_Code", "0").equals("0")) {
				Toast.makeText(this, "아직 유치원밤에 연결되지 않은 선생님정보입니다. 관리자에 문의해주세요",
						Toast.LENGTH_LONG).show();
				sendMessage(LOGIN_STARTACTIVITY); // 로그인창.
			} else {
				Toast.makeText(this, "회원정보에 문제가 있거나 내부오류입니다.",
						Toast.LENGTH_LONG).show();
				sendMessage(LOGIN_STARTACTIVITY);
			}

			break;
		case LOGIN_STARTACTIVITY: // 저장된 정보 없거나 잘못되서 로그인페이지로 이동
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}

			startActivity(new Intent(this, Intro_Login_A.class).putExtra(
					INTENT_EXTRA_INTRO_UUID, regId));
			finish();
			break;
		case LOGIN_CHECK: // 저장된 정보있는지 검사흐름

			if (autologin) {
				startNetwork(1); // 쉐어프리퍼런스 내용있으면 비교스레드.
			} else {

				startNetwork(2); // 로그인으로.
			}

			break;
		case FAIR_VERSION: // 버전 얻어오는데 실패
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "버전 정보를 얻는데 실패했습니다.", Toast.LENGTH_LONG)
					.show();
			break;
		case UPDATE_VERSION: // 저장된 정보있는지 검사흐름
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			AlertDialog alert;
			AlertDialog.Builder builder = new AlertDialog.Builder(
					Intro_Intro_A.this);
			builder.setMessage("버전이 바뀌었습니다 구글 스토어에서 업데이트해주세요")
					.setCancelable(false)
					.setPositiveButton("업데이트",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									try {
									    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+getPackageName())));
									} catch (android.content.ActivityNotFoundException anfe) {
									    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="+getPackageName())));
									}
								}
							})
					.setNegativeButton("종료",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									finish();
								}
							});
			alert = builder.create();
			alert.show();
			break;
		}

	}

	// gcm uuid 얻기 위해 선언한 메소드들
	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging
								.getInstance(getApplicationContext());
					}
					regId = gcm.register(BasicInfo.PROJECT_ID);
					msg = "Device registered, registration ID=" + regId;

					storeRegistrationId(regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();

				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				sendMessage(LOGIN_CHECK);
			}
		}.execute(null, null, null);
	}

	private void storeRegistrationId(String regId) {
		int appVersion = getAppVersion();
		BasicInfo.resid = regId;
		BasicInfo.appversion = appVersion;
	}

	// 버전체크
	private int getAppVersion() {
		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(
					getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000)
						.show();
			} else {
				finish();
			}
			return false;
		}
		return true;
	}

	// 자동 로그인여부 검사
	private void checkPreferences() {
		email = member.getString("PK_Mem_Email", "");
		pass = member.getString("Mem_Pass", "");
		if (email == "" || pass == "") {
			autologin = false;
		} else {
			autologin = true;
		}
	}

	// 로그인하고 uuid저장하는 thread의 동작부분
	private void mainThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_LOGIN_CHECK, "uuid=" + regId + "&email=" + email
							+ "&pass=" + pass));
			if (jsonObject.getBoolean("success")) {
				if (setPreferencesMember(jsonObject.getString("payload"))) { // 학원정보
																				// 저장.

					onNetworkCallback(SELECT_STARTACTIVITY, "");
				} else {

					onNetworkCallback(LOGIN_STARTACTIVITY,
							jsonObject.getString("message")); // 로그인으로.
				}
			} else {
				onNetworkCallback(LOGIN_STARTACTIVITY, "");// 로그인으로.
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	private boolean setPreferencesMember(String msg) {
		try {
			JSONObject jsonObject = new JSONObject(msg);
			SharedPreferences.Editor editora = member.edit();
			editora.putString("PK_Mem_Email",
					jsonObject.getString("PK_Mem_Email"));
			editora.putString("Mem_Pass", member.getString("Mem_Pass", ""));
			editora.putString("FK_Sch_Mem_Code",
					jsonObject.getString("FK_Sch_Mem_Code"));
			editora.putString("FK_Cla_Mem_Code",
					jsonObject.getString("FK_Cla_Mem_Code"));
			editora.putString("Mem_Phone", jsonObject.getString("Mem_Phone"));
			editora.putString("Mem_Name", jsonObject.getString("Mem_Name"));
			editora.putString("Mem_CreateDate",
					jsonObject.getString("Mem_CreateDate"));
			editora.putString("Mem_Uuid", jsonObject.getString("Mem_Uuid"));
			editora.putString("Mem_Rank", jsonObject.getString("Mem_Rank"));
			editora.putString("Mem_Connect",
					jsonObject.getString("Mem_Connect"));
			editora.putString("Mem_Birth", jsonObject.getString("Mem_Birth"));
			editora.putString("Mem_Confirm",
					jsonObject.getString("Mem_Confirm"));
			editora.commit();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
			return false;
		}
		return true;
	}

	private String getVersion() {

		PackageInfo pi = null;

		try {

			pi = getPackageManager().getPackageInfo(getPackageName(), 0);

		} catch (NameNotFoundException e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		return pi.versionName;
	}

	private boolean setPreferencesSchool(String msg) {
		try {
			JSONObject jsonObject = new JSONObject(msg);
			SharedPreferences.Editor editora = school.edit();
			editora.putString("PK_Sch_Code",
					jsonObject.getString("PK_Sch_Code"));
			editora.putString("FK_Add_Sch_Code",
					jsonObject.getString("FK_Add_Sch_Code"));
			editora.putString("Sch_Name", jsonObject.getString("Sch_Name"));
			editora.putString("Sch_Add", jsonObject.getString("Sch_Add"));
			editora.putString("Sch_Info", jsonObject.getString("Sch_Info"));
			editora.commit();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
			return false;
		}
		;
		return true;
	}

	private boolean checkVersion() {

		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_VERSION, ""));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				msg = new JSONObject(msg).getString("Waukids");
				msg = msg.replace("d", ".");
				
				Log.i("ddd", Double.parseDouble(msg) + " " + Double.parseDouble(getVersion()));
				if (Double.parseDouble(msg)>Double.parseDouble(getVersion())) { // 학원정보저장.
					onNetworkCallback(UPDATE_VERSION, "");
					return false;
				} else {
					return true;
				}
			} else {
				onNetworkCallback(FAIR_VERSION, "");
				return true;
			}
		} catch (Exception e) {
			onNetworkCallback(FAIR_VERSION, e.toString());
		}
		;
		return true;
	}

	
}
